package com.web.surf.sample.eshop.faces.core;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.web.surf.sample.eshop.dto.interfaces.IProperty;

/**
 * Class that realize basic conception of all substances
 * 
 * @author LukyanyukDV
 * 
 */
public abstract class AbstractBean {

	/**
	 * Substance properties
	 */
	protected Map<IProperty, Object> properties = new HashMap<IProperty, Object>();

	protected String generateID() {
		return UUID.randomUUID().toString();
	}

	public void addProperty(IProperty propertyName, Object propertyValue) {
		properties.put(propertyName, propertyValue);
	}

	public <T> T getProperty(IProperty propertyName, Class<T> type ) {
		try {
			Object propertyValue = properties.get(propertyName);
			if (propertyValue == null) {
				try {
					return type.newInstance();
				} catch (InstantiationException e) {
					return (T) type.getConstructor(String.class).newInstance("0");	
				}						
			} else {		
				return (T) properties.get(propertyName);
			}
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} 
	}
}